namespace FIREFLYX {
    /** */
    export class Graphics {
        private static readonly help_Rect = new Rect(0, 0, 1, 1);
        private static _blitMtr: Material;

        public static init() {
            //blit material
            const sh = DefaultAsset.GetShader(BUILTIN_SHADER_POSTEFF_IMAGE);
            this._blitMtr = new Material("blitMtr");
            this._blitMtr.shader = sh;
        }

        /**
         * 绘制一个全屏的 quad
         * @param material 绘制的材质
         * @param viewPortRect 绘制设置的viewport
         */
        public static DrawFullQuad(material: Material, viewPortRect: Rect) {
            const renderCtx = SceneManager.renderContext;
            const gl = renderCtx.webgl2;
            const quadMesh = DefaultAsset.GetMesh(DefMesh.QUAD_FULL_CLIP);
            const sh = material.shader;
            const cSH = sh.getCompiled(material.getKeywordID()) as ShaderCompiled;
            const sp = cSH.program as WebGLProgram;
            //viewport set
            gl.viewport(viewPortRect.x, viewPortRect.y, viewPortRect.w, viewPortRect.h);
            //pass clear
            gl.clearColor(0, 0, 0, 0);    //backclear color
            gl.clearDepth(1.0);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

            //WebGLProgram use
            gl.useProgram(sp);
            //vao
            gl.bindVertexArray(quadMesh.VAO);   //启用vao
            //uniform 数据提交
            material.uploadUniform(renderCtx);
            //纹理Activator
            renderCtx.textrueActivator.reset();

            //绘制贴屏片 后渲染效果
            gl.drawElements(gl.TRIANGLES, quadMesh.elementLenght, quadMesh.elementType, 0);

            //绘制完毕清理状态
            gl.bindVertexArray(null);
        }

        /**
         * 绘制到纹理
         */
        public static DrawTexture() {
            //

        }

        /**
         * 使用着色器将源纹理复制到目标渲染纹理中（主要用于后处理效果）
         * @param src 源纹理
         * @param dest 目标渲染纹理
         * @param material 渲染材质
         */
        public static Blit(src: TextureBase, dest: RenderTexture2D, material?: Material) {
            //
            if (!src || !dest) return;
            const mtr = material ? material : this._blitMtr;
            const gl = App.webgl2;
            const rect = this.help_Rect;
            //材质设置
            mtr.setProperty("u_mainTex", src);
            //设置 viewport size
            rect.set(0, 0, dest.width, dest.height);    //绘制viewport 对齐 dest的大小
            //enable fbo
            gl.bindFramebuffer(gl.FRAMEBUFFER, dest.fbo);
            //绘制
            this.DrawFullQuad(mtr, rect);

            //清理状态
            gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        }
    }
}